#include "xplayer.h"
#include "xaudio_play.h"
#include "xvideo_view.h"

void XPlayer::Stop() {
  XThread::Stop();
  demux_.Stop();
  audio_decode_.Stop();
  video_decode_.Stop();
  if (view_) {
    view_->Close();
    delete view_;
    view_ = nullptr;
  }
  XAudioPlay::Instance()->Close();
}

void XPlayer::SetSpeed(float s) { XAudioPlay::Instance()->SetSpeed(s); }

bool XPlayer::Open(const char *url, void *winId) {
  // 解封装
  if (!demux_.Open(url)) {
    return false;
  }
  auto vp = demux_.CopyVideoPara();
  if (vp) {
    this->total_ms_ = vp->total_ms;
    if (!video_decode_.Open(vp->para)) {
      return false;
    }
    video_decode_.set_stream_index(demux_.video_index());
    if (!view_) {
      view_ = XVideoView::Create();
    }
    view_->set_win_id(winId);
    if (!view_->Init(vp->para)) {
      return false;
    }
  }
  auto ap = demux_.CopyAudioPara();
  if (ap) {
    if (!audio_decode_.Open(ap->para)) {
      return false;
    }
    audio_decode_.set_frame_cache(true);
    audio_decode_.set_stream_index(demux_.audio_index());
    // 初始化音频播放
    XAudioPlay::Instance()->Open(*ap);
  } else {
    demux_.set_syn_type(XSYN_VIDEO);
  }
  demux_.set_next(this);
  return true;
}

bool XPlayer::Seek(long long pos) {
  demux_.Seek(pos);
  audio_decode_.Clear();
  video_decode_.Clear();
  XAudioPlay::Instance()->Clear();
  return true;
}

void XPlayer::Pause(bool is_pause) {
  if (is_pause == this->is_pause_)
    return;
  XThread::Pause(is_pause);
  demux_.Pause(is_pause);
  audio_decode_.Pause(is_pause);
  video_decode_.Pause(is_pause);
  XAudioPlay::Instance()->Pause(is_pause);
}

void XPlayer::Do(AVPacket *pkt) {
  if (audio_decode_.is_open()) {
    audio_decode_.Do(pkt);
  }
  if (video_decode_.is_open()) {
    video_decode_.Do(pkt);
  }
}

void XPlayer::Start() {
  demux_.Start();
  if (video_decode_.is_open()) {
    video_decode_.Start();
  }
  if (audio_decode_.is_open()) {
    audio_decode_.Start();
  }
  XThread::Start();
}

void XPlayer::Update() {
  if (view_) {
    auto f = video_decode_.GetFrame();
    if (f) {
      std::cout << "q" << std::endl;
      view_->DrawFrame(f);
      XFreeFrame(&f);
    }
  }
  // 音频播放
  auto au = XAudioPlay::Instance();
  auto f = audio_decode_.GetFrame();
  if (!f) {
    return;
  }
  au->Push(f);
  XFreeFrame(&f);
}

void XPlayer::Main() {
  long long syn = 0;
  auto au = XAudioPlay::Instance();
  auto ap = demux_.CopyAudioPara();
  auto vp = demux_.CopyVideoPara();
  video_decode_.set_time_base(vp->time_base);
  // 线程主要用来同步
  while (!is_exit_) {
    if (is_pause()) {
      MSleep(5);
      continue;
    }
    // 当前播放的时间
    this->pos_ms_ = video_decode_.cur_ms();
    if (ap) {
      syn = XResacle(au->cur_pts(), ap->time_base, vp->time_base);
      audio_decode_.set_syn_pts(au->cur_pts() + 10000);
      video_decode_.set_syn_pts(syn);
    }
    MSleep(1);
  }
}
